package org.vacoor.xqq.ui.util;

import java.awt.*;
import java.net.URL;

/**
 * User: vacoor
 */
public class ImageLoader {
    private static MediaTracker tracker;
    private static int trackerID;
    private static final Object trackerMonitor = new Object();

    /**
     * 加载图片, 等待延迟加载完毕才返回
     * 该方法调用 {@link Toolkit#getImage(java.net.URL)}, 因此将会存在缓存问题
     *
     * @param url
     * @return
     */
    public static Image getImage(URL url) {
        Image image = Toolkit.getDefaultToolkit().getImage(url);
        loadImage(image);
        return image;
    }

    /**
     * 等待延迟加载完成
     * @param image the image
     */
    protected static void loadImage(Image image) {
        MediaTracker mTracker = getTracker();
        synchronized (mTracker) {
            int id = getNextID();

            mTracker.addImage(image, id);
            try {
                mTracker.waitForID(id, 0);
            } catch (InterruptedException e) {
                System.out.println("INTERRUPTED while loading Image");
            }
            mTracker.removeImage(image, id);
        }
    }

    private static int getNextID() {
        synchronized (getTracker()) {
            return ++trackerID;
        }
    }

    private static MediaTracker getTracker() {
        if (tracker != null) {
            return tracker;
        }

        synchronized (trackerMonitor) {
            if (tracker == null) {
                tracker = new MediaTracker(new Component() {
                });
            }
        }
        return tracker;
    }
}
